<template>
  <div class="bw-node-attr-data-obj-select">
    <a-select
      v-bind="attrs"
      v-model:value="content"
      :style="{ width: '100%', overflow: 'auto' }"
      :mode="'tags'"
      :showSearch="true"
      optionFilterProp="label"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { api, useAxiosResponse } from '/@/api'
import { BwPageResultOutputSysDataObjectAppGetFieldOutput } from '@bitwit/tenantapi'
import { DefaultOptionType } from 'ant-design-vue/es/select'

const emit = defineEmits(['update:value'])
const props = withDefaults(
  defineProps<{
    value?: string | number
    options?: DefaultOptionType[]
    dataObjId?: number | string
    [key: string]: any
  }>(),
  {}
)

const content = computed({
  get: () => {
    return props.value ? [props.value] : undefined
  },
  set: (value) => {
    let _value: string | number
    if (Array.isArray(value)) {
      _value = value[value.length - 1]
      emit('update:value', _value)
    } else {
      emit('update:value', value)
    }
  },
})

const curOptions = ref<DefaultOptionType[]>([])

const attrs = computed(() => {
  return {
    showSearch: true,
    optionFilterProp: 'label',
    ...props,
    options: curOptions.value,
  }
})

const getOptions = (dataObjectId?: string | number) => {
  return new Promise((resolve, reject) => {
    api
      .apiSysDataObjectGetFieldsPost({
        dataObjectId: dataObjectId?.toString(),
      })
      .then((res) => {
        const resData =
          useAxiosResponse<BwPageResultOutputSysDataObjectAppGetFieldOutput>(
            res
          )
        curOptions.value =
          resData?.rows?.map((item) => {
            return {
              label: item.code ?? '未命名字段',
              value: item.id,
            }
          }) ?? []
        resolve(resData)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

watch(
  () => props.dataObjId,
  (newVal) => {
    getOptions(newVal)
  },
  { immediate: true, deep: true }
)
</script>

<style lang="less" scoped>
.bw-node-attr-data-obj-select {
  width: 100%;
  height: auto;
  .ant-select {
    width: 100%;
  }
}
</style>
